package com.raycloud.action.user;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.raycloud.action.common.BaseAction;
import com.raycloud.common.Constants;
import com.raycloud.dao.dbhash.DbHashUtil;
import com.raycloud.domain.User;
import com.raycloud.domain.UserRelation;
import com.raycloud.manager.UserRelationMgr;

public class FollowAction extends BaseAction implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(FollowAction.class);

	private long id;
	private String type;
	
	private UserRelationMgr userRelationMgr;
	
	public String execute() throws Exception {
		if("ajax".equals(type)) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			try {
				followBiz();
				out.print(1);
			} catch (Exception e) {
				out.print("关注失败，可能原因是: " + e.getMessage());
				logger.error(e.getMessage(), e);
			} finally {
				if(out != null){
					out.close();
				}
			}
		}else{
			followBiz();
			return SUCCESS;
		}
		return null;
	}
	
	private void followBiz(){
		User user = (User) session.get("user");
		UserRelation userRelation = new UserRelation();
		userRelation.setDbId(DbHashUtil.getUserRelationDBId(user.getId()));
		userRelation.setFollowId(id);
		userRelation.setUserId(user.getId());
		userRelation.setType(Constants.FOLLOW_RELATION);
		
		UserRelation userRelation2 = new UserRelation();
		userRelation2.setUserId(id);
		userRelation2.setFollowId(user.getId());
		userRelation2.setType(Constants.FANS_RELATION);
		userRelation2.setDbId(DbHashUtil.getUserRelationDBId(id));
		
		userRelationMgr.insertOrUpdateFollowRelations(userRelation, userRelation2);
		user.setFollowCount(user.getFollowCount() + 1);
	}

	public void setId(long id) {
		this.id = id;
	}

	public void setUserRelationMgr(UserRelationMgr userRelationMgr) {
		this.userRelationMgr = userRelationMgr;
	}

	public void setType(String type) {
		this.type = type;
	}
}
